/**
 * Created by guomin on 2017/5/31.
 */
var Promise = require('bluebird');
var validator = require('validator');
var urlencode=require('urlencode');
var crypto=require('crypto');
var client = require('../conf/redis');

var checkParams = {
//参数是否完整
  isDefined:function(params,filedNames){
    return new Promise(function(resolve,reject){
      for(var i=0;i<filedNames.length;i++){
        if(!(filedNames[i] in params)){
          reject(-23);
        }
      }
      resolve(true);
    });
  },
  //参数是否为空
  isParamsEmpty:function(params,filedNames){
    return new Promise(function(resolve,reject){
      for(var i=0;i<filedNames.length;i++){
        var filed=filedNames[i];
        if(params[filed].length==0){
          reject(-23);
        }
      }
      resolve(true);
    });
  },
  //手机号码格式验证
  isMobile:function(mobile){
    return new Promise(function(resolve,reject){
      var regMobile=/^0?1[3|4|5|7|8]\d{9}$/;
      if(regMobile.test(mobile)){
        resolve(true);
      }else{
        reject(-12);
      }
    });
  },
  //验证code是否正确
  isRightCode:function(params,data){
    return new Promise(function(resolve,reject){
      var clientCode=params.code;
      var mobile=params.mobile;
      var decodeContent=decodeURI(params.content);
      var encodeContent=urlencode(decodeContent);
      var reg=/%20/g;
      var con=encodeContent.replace(reg,"+");
      var codeStr=data.secretKey+mobile+con;
      var md5=crypto.createHash('md5');
      md5.update(codeStr);
      var serverCode=md5.digest('hex');
      console.log("serverCode__________",serverCode);
      if(clientCode!=serverCode){
        reject(-11);
      }else{
        resolve(true);
      }
    });
  },
  //30s内同一手机号重复发送
  isRepeatedMobile:function(mobile){
    return new Promise(function(resolve,reject){
      client.get('mobile',function (err,reply) {
        if(err){
          reject(err);
        }
        if(reply){
          console.log("mobile is repeated in 30s ...");
          reject(-13);
        }else{
          resolve(true);
        }
      })
    });
  }
};

exports = module.exports = checkParams;